#=00
from __future__ import with_statement
from contextlib import contextmanager
import sqlite3
#=01 contextmanager decorator
@contextmanager #01
def transaction (connection): 
    cursor = connection.cursor()
    try:
#=02 yield the value used
        yield cursor  #02
#=03 if an exception occurs
    except: #03
        connection.rollback() #03
        raise #03
#=04 no exception - proceed
    else:  #04
        connection.commit() #04

#=05 using the context manager
dbconn = sqlite3.connect('userdb.sqlite') #05
with transaction(dbconn) as cursor: #05
#=06 calls rollback/commit after this
    cursor.execute("insert into users"  #06
                   "( username, realname )" #06
                   "values ('%s', '%s')"%  #06
                   ('anthony', 'Anthony Baxter'))  #06
